import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

// API 响应接口
export interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: string
}

// 创建 axios 实例
const createApiClient = (): AxiosInstance => {
  const client = axios.create({
    baseURL: '/api',
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
    },
  })

  // 请求拦截器 - 自动添加认证头
  client.interceptors.request.use(
    (config) => {
      // 只在客户端环境中访问 localStorage
      if (typeof window !== 'undefined') {
        const token = localStorage.getItem('auth_token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
      }
      return config
    },
    (error) => {
      return Promise.reject(error)
    }
  )

  // 响应拦截器 - 统一处理响应和错误
  client.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>) => {
      // 如果后端返回的 success 为 false，抛出错误
      if (response.data && response.data.success === false) {
        const error = new Error(response.data.error || response.data.message || 'Request failed')
        ;(error as any).response = response
        return Promise.reject(error)
      }
      return response
    },
    (error) => {
      // 处理 401 未授权错误
      if (error.response?.status === 401) {
        // 只在客户端环境中清除本地存储的认证信息
        if (typeof window !== 'undefined') {
          localStorage.removeItem('auth_token')
          localStorage.removeItem('auth_user')
          window.location.href = '/login'
        }
      }
      
      // 统一错误格式
      const message = error.response?.data?.message || 
                     error.response?.data?.error || 
                     error.message || 
                     'Network error'
      
      const customError = new Error(message)
      ;(customError as any).status = error.response?.status
      ;(customError as any).response = error.response
      
      return Promise.reject(customError)
    }
  )

  return client
}

// 导出单例实例
export const apiClient = createApiClient()

// 便捷的 API 方法
export const api = {
  // GET 请求
  get: <T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    apiClient.get(url, config).then(res => res.data),

  // POST 请求
  post: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    apiClient.post(url, data, config).then(res => res.data),

  // PUT 请求
  put: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    apiClient.put(url, data, config).then(res => res.data),

  // DELETE 请求
  delete: <T = any>(url: string, config?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    apiClient.delete(url, config).then(res => res.data),

  // PATCH 请求
  patch: <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<ApiResponse<T>> =>
    apiClient.patch(url, data, config).then(res => res.data),
}

export default api
